const { parseString } = require('xml2js');

class Common {
  parseStringXml(xml) {
    return new Promise((resolve, reject) => {
      parseString(xml, async (err, result) => {
        if (!err) {
          const xmlData = result.xml;
          const { MsgType, ToUserName, FromUserName, Event, Content } = xmlData;
          const createTime = Date.parse(new Date());
          const msgType = MsgType[0]; // 消息类型，event
          const toUserName = ToUserName[0]; // 开发人员微信号
          const toFromName = FromUserName[0]; // 发送方帐号（一个OpenID）
          const event = Event ? Event[0] : ''; // 事件类型，subscribe(订阅)、unsubscribe(取消订阅)
          const msgContent = Content ? Content[0] : ''; // 消息内容
          resolve({
            createTime,
            msgType,
            toUserName,
            toFromName,
            event,
            msgContent,
          });
        } else {
          console.log('err******', err);
          reject(new Error('解析失败'));
        }
      });
    });
  }
}

module.exports = new Common();
